const { graphql, buildSchema } = require("graphql");
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const cors = require("cors");
const { v4: uuidv4 } = require("uuid");

const app = express();
app.use(cors());

const articles = [
  {
    id: "1",
    title: "GraphQL 入门教程",
    body: "GraphQL 是一个用于 API 的查询语言",
  },
  { id: "2", title: "GraphQL 实战", body: "GraphQL 实战教程" },
  { id: "3", title: "GraphQL 核心概念", body: "GraphQL 核心概念讲解" },
];

// 1. 使用GraphQL schema语法构建一个 schema
const schema = buildSchema(`
  type Article {
    id: ID!
    title: String!
    body: String!
    tagList: [String!]
  }

  # 查询入口
  type Query {
    articles: [Article]
    article(id: ID!): Article
  }

  # 参数类型必须使用 Input 定义
  input createArticle {
    title: String!
    body: String!
    tagList: [String!]
  }

  type DeleteStatas {
    success: Boolean!
  }

  # 修改入口
  type Mutation {
    createArticle(article: createArticle!): Article
    updateArticle(id: ID!, article: createArticle!): Article
    deleteArticle(id: ID!): DeleteStatas
  }
`);

// 2. 定义 resolver 函数，用于处理 GraphQL 请求
const rootValue = {
  articles() {
    return articles;
  },

  article({ id }) {
    const article = articles.find((article) => article.id === id);
    return article;
  },

  createArticle({ article }) {
    article.id = uuidv4();
    articles.push(article);
    return article;
  },

  updateArticle({ id, article }) {
    const index = articles.findIndex((article) => article.id === id);
    if (index === -1) {
      throw new Error("Article not found");
    }
    articles[index] = {
      ...articles[index],
      ...article,
    };
    return articles[index];
  },

  deleteArticle({ id }) {
    const index = articles.findIndex((article) => article.id === id);
    if (index === -1) {
      throw new Error("Article not found");
    }
    articles.splice(index, 1);
    return { success: true };
  },
};

// 3. 创建 Express 应用
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    rootValue,
    graphiql: true, // 开启浏览器 GraphQL IDE 调试工具
  })
);

app.listen(4000, () => {
  console.log("Server running at http://localhost:4000/graphql");
});

// 3. 查询
/* graphql(schema, "{ foo }", rootValue).then((result) => {
  console.log(result);
}); */
